package com.foftact.blockposition.controller;

import com.foftact.blockposition.BlockPosition;
import com.foftact.blockposition.service.BlockPositionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 板块成分股控制器
 */
@Controller
@RequestMapping("/blockposition")
public class BlockPositionController {
    private static final Logger logger = LoggerFactory.getLogger(BlockPositionController.class);
    
    @Autowired
    private BlockPositionService blockPositionService;
    
    /**
     * 跳转到板块成分股列表页面
     * @param model 模型对象
     * @return 页面路径
     */
    @GetMapping("/list")
    public String listPage(Model model) {
        return "blockposition/list";
    }
    
    /**
     * 获取板块成分股数据列表
     * @param blockCode 板块代码（可选）
     * @return 数据列表
     */
    @GetMapping("/data")
    @ResponseBody
    public List<BlockPosition> getDataList(@RequestParam(required = false) String blockCode) {
        try {
            logger.info("获取板块成分股数据列表，板块代码：{}", blockCode);
            if (blockCode != null && !blockCode.trim().isEmpty()) {
                return blockPositionService.getBlockPositionsByBlockCode(blockCode);
            } else {
                return blockPositionService.getAllBlockPositions();
            }
        } catch (Exception e) {
            logger.error("获取板块成分股数据列表失败", e);
            throw new RuntimeException("获取板块成分股数据列表失败", e);
        }
    }
    
    /**
     * 手动抓取板块成分股数据
     * @return 结果信息
     */
    @PostMapping("/fetch")
    @ResponseBody
    public Map<String, Object> fetchData(String blockCode) {
        try {
            logger.info("手动抓取板块成分股数据");
            int savedCount = blockPositionService.fetchAndSaveBlockPositionData(blockCode);
            return Map.of(
                "success", true,
                "message", "抓取成功，共保存" + savedCount + "条数据"
            );
        } catch (Exception e) {
            logger.error("手动抓取板块成分股数据失败", e);
            return Map.of(
                "success", false,
                "message", "抓取失败：" + e.getMessage()
            );
        }
    }
    
    /**
     * 获取单个板块成分股详情
     * @param marketCode 市场码
     * @param code 股票代码
     * @return 板块成分股详情
     */
    @GetMapping("/detail")
    @ResponseBody
    public BlockPosition getDetail(@RequestParam Integer marketCode, @RequestParam String code) {
        try {
            logger.info("获取板块成分股详情，市场码：{}，股票代码：{}", marketCode, code);
            return blockPositionService.getBlockPositionByMarketCodeAndCode(marketCode, code);
        } catch (Exception e) {
            logger.error("获取板块成分股详情失败", e);
            throw new RuntimeException("获取板块成分股详情失败", e);
        }
    }
    
    /**
     * 跳转到板块成分股统计页面
     * @param model 模型对象
     * @return 页面路径
     */
    @GetMapping("/statistics")
    public String statisticsPage(Model model) {
        return "blockposition/statistics";
    }
    
    /**
     * 获取统计数据
     * @return 统计数据
     */
    @GetMapping("/statisticsData")
    @ResponseBody
    public Map<String, Object> getStatisticsData() {
        try {
            List<BlockPosition> allPositions = blockPositionService.getAllBlockPositions();
            
            // 按板块统计成分股数量
            Map<String, Long> blockCountMap = allPositions.stream()
                .collect(Collectors.groupingBy(BlockPosition::getBlockCode, Collectors.counting()));
            
            // 按市场统计成分股数量
            Map<Integer, Long> marketCountMap = allPositions.stream()
                .collect(Collectors.groupingBy(BlockPosition::getMarketCode, Collectors.counting()));
            
            return Map.of(
                "totalCount", allPositions.size(),
                "blockCountMap", blockCountMap,
                "marketCountMap", marketCountMap
            );
        } catch (Exception e) {
            logger.error("获取统计数据失败", e);
            throw new RuntimeException("获取统计数据失败", e);
        }
    }
}